package com.aternity.geolocations.firebird;

import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

/**
 * @author Daniel Orr
 * @since 12/18/13 12:38 PM
 */
public class RectangleFormatter {

    /**
     * Formats a string for the given rectangle.<p>
     * Example string: [x=30.6387,y=-22.3416,w=0.4736,h=0.0494]
     *
     * @param rectangle2D any rectangle
     * @return formatted string.
     */
    public String format(Rectangle2D rectangle2D) {
        StringBuilder sb = new StringBuilder("[");
        sb.append("x=");
        sb.append(rectangle2D.getX());
        sb.append(",");
        sb.append("y=");
        sb.append(rectangle2D.getY());
        sb.append(",");
        sb.append("w=");
        sb.append(rectangle2D.getWidth());
        sb.append(",");
        sb.append("h=");
        sb.append(rectangle2D.getHeight());
        sb.append("]");
        return sb.toString();
    }

    /**
     * Formats a list of rectangles.
     *
     * @param rectangles list of rectangles.
     * @return formatted string.
     */
    public String formatMultiRectangles(List<Rectangle2D> rectangles) {
        StringBuilder sb = new StringBuilder("{");
        for (int i = 0; i < rectangles.size(); i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(format(rectangles.get(i)));
        }
        sb.append("}");
        return sb.toString();
    }

    public List<Rectangle2D> parseMultiRectangles(String s) {
        Pattern p = Pattern.compile("\\[(.*?)\\]", Pattern.DOTALL);
        Matcher matcher = p.matcher(s);
        List<Rectangle2D> rectangles = new ArrayList<>();
        while (matcher.find()) {
            String polygonStr = matcher.group(1);
            rectangles.add(parse(polygonStr));
        }
        return rectangles;
    }

    /**
     * @param s
     * @return
     */
    public Rectangle2D parse(String s) {
        String r = s;
        if(r.startsWith("{[")){
            r = r.substring(2);
        }
        if(r.endsWith("]}")){
            r = r.substring(0, r.length()-2);
        }
        String[] splits = StringUtils.split(r, ",");
        double x = extractValue(splits[0]);
        double y = extractValue(splits[1]);
        double w = extractValue(splits[2]);
        double h = extractValue(splits[3]);
        return new Rectangle2D.Double(x, y, w, h);
    }

    private double extractValue(String split) {
        int i = split.indexOf('=');
        return Double.parseDouble(split.substring(i + 1));
    }
}
